package com.ruoyi.toobit.task;

import com.ruoyi.toobit.service.TooBitApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * TooBit API定时任务
 * 每分钟执行一次验签请求，监控API连接状态
 * 
 * @author TooBit
 * @date 2025-01-06
 */
@Component
public class TooBitApiScheduledTask {
    
    private static final Logger log = LoggerFactory.getLogger(TooBitApiScheduledTask.class);
    
    @Autowired
    private TooBitApiService tooBitApiService;
    
    // 统计信息
    private long totalRequests = 0;
    private long successRequests = 0;
    private long failedRequests = 0;
    private String lastExecutionTime = "";
    private String lastExecutionStatus = "";
    
    /**
     * 每分钟执行一次的TooBit API验签请求任务
     * 使用cron表达式: 每分钟的第0秒执行
     */
    @Scheduled(cron = "0 * * * * ?")
    public void executeExchangeInfoTask() {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        totalRequests++;
        
        log.info("⏰ === TooBit API定时任务执行 === [{}]", currentTime);
        log.info("📊 任务统计: 总执行{}次, 成功{}次, 失败{}次", totalRequests, successRequests, failedRequests);
        
        try {
            // 执行验签请求
            String response = tooBitApiService.getExchangeInfoWithSignature();
            
            if (response != null && !response.isEmpty()) {
                successRequests++;
                lastExecutionStatus = "SUCCESS";
                
                // 分析响应数据
                int symbolCount = countOccurrences(response, "\"symbol\":");
                boolean hasServerTime = response.contains("serverTime");
                
                log.info("✅ 定时任务执行成功!");
                log.info("🏪 获取交易对数量: {} 个", symbolCount);
                log.info("🕐 服务器时间同步: {}", hasServerTime ? "正常" : "异常");
                
                // 输出关键交易对信息（从实际API响应中解析）
                logKeyTradingPairs(response);
                
            } else {
                failedRequests++;
                lastExecutionStatus = "FAILED";
                log.error("❌ 定时任务执行失败: API响应为空");
            }
            
        } catch (Exception e) {
            failedRequests++;
            lastExecutionStatus = "ERROR";
            log.error("🚨 定时任务执行异常: {}", e.getMessage(), e);
        }
        
        lastExecutionTime = currentTime;
        
        // 输出任务执行总结
        double successRate = totalRequests > 0 ? (double) successRequests / totalRequests * 100 : 0;
        log.info("📈 任务成功率: {:.2f}% ({}/{})", successRate, successRequests, totalRequests);
        log.info("⏰ === TooBit API定时任务完成 === [{}]", currentTime);
        log.info("");
    }
    
    /**
     * 每5分钟执行一次的完整验签任务
     * 使用HMAC SHA256完整签名验证
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void executeFullSignatureTask() {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        log.info("🔐 === TooBit API完整验签任务执行 === [{}]", currentTime);
        
        try {
            // 执行完整验签请求
            String response = tooBitApiService.getExchangeInfoWithFullSignature();
            
            if (response != null && !response.isEmpty()) {
                log.info("✅ 完整验签任务执行成功!");
                log.info("🔐 HMAC SHA256签名验证: 通过");
                
                // 验证API连接状态
                Map<String, Object> connectionStatus = tooBitApiService.validateApiConnection();
                log.info("🌐 API连接状态: {}", connectionStatus.get("status"));
                
            } else {
                log.error("❌ 完整验签任务执行失败");
            }
            
        } catch (Exception e) {
            log.error("🚨 完整验签任务异常: {}", e.getMessage(), e);
        }
        
        log.info("🔐 === TooBit API完整验签任务完成 === [{}]", currentTime);
    }
    
    /**
     * 每30分钟执行一次的API连接状态检查
     */
    @Scheduled(cron = "0 */30 * * * ?")
    public void executeConnectionHealthCheck() {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        log.info("🏥 === TooBit API健康检查 === [{}]", currentTime);
        
        try {
            Map<String, Object> healthStatus = tooBitApiService.validateApiConnection();
            
            String status = (String) healthStatus.get("status");
            Long responseTime = (Long) healthStatus.get("responseTime");
            Integer symbolCount = (Integer) healthStatus.get("symbolCount");
            
            if ("connected".equals(status)) {
                log.info("✅ API健康状态: 正常");
                log.info("📊 响应时间: {}ms", responseTime);
                log.info("🏪 交易对数量: {} 个", symbolCount);
                
                // 输出统计信息
                outputTaskStatistics();
                
            } else {
                log.warn("⚠️ API健康状态: 异常 - {}", healthStatus.get("error"));
            }
            
        } catch (Exception e) {
            log.error("🚨 API健康检查异常: {}", e.getMessage(), e);
        }
        
        log.info("🏥 === TooBit API健康检查完成 === [{}]", currentTime);
    }
    
    /**
     * 输出关键交易对信息
     */
    private void logKeyTradingPairs(String response) {
        try {
            // 检查主要交易对是否存在
            String[] keyPairs = {"BTCUSDT", "ETHUSDT", "DOGEUSDT", "TRXUSDT"};
            
            for (String pair : keyPairs) {
                if (response.contains("\"" + pair + "\"")) {
                    log.debug("🔍 发现关键交易对: {}", pair);
                }
            }
            
        } catch (Exception e) {
            log.debug("🔍 解析交易对信息时出错: {}", e.getMessage());
        }
    }
    
    /**
     * 输出任务统计信息
     */
    private void outputTaskStatistics() {
        log.info("📊 === TooBit API任务统计 ===");
        log.info("   总执行次数: {} 次", totalRequests);
        log.info("   成功次数: {} 次", successRequests);
        log.info("   失败次数: {} 次", failedRequests);
        log.info("   成功率: {:.2f}%", totalRequests > 0 ? (double) successRequests / totalRequests * 100 : 0);
        log.info("   最后执行时间: {}", lastExecutionTime);
        log.info("   最后执行状态: {}", lastExecutionStatus);
    }
    
    /**
     * 计算字符串中指定子串的出现次数
     */
    private int countOccurrences(String text, String pattern) {
        if (text == null || pattern == null) {
            return 0;
        }
        
        int count = 0;
        int index = 0;
        while ((index = text.indexOf(pattern, index)) != -1) {
            count++;
            index += pattern.length();
        }
        return count;
    }
    
    /**
     * 获取任务统计信息（供外部调用）
     */
    public Map<String, Object> getTaskStatistics() {
        Map<String, Object> stats = new java.util.HashMap<>();
        stats.put("totalRequests", totalRequests);
        stats.put("successRequests", successRequests);
        stats.put("failedRequests", failedRequests);
        stats.put("successRate", totalRequests > 0 ? (double) successRequests / totalRequests * 100 : 0);
        stats.put("lastExecutionTime", lastExecutionTime);
        stats.put("lastExecutionStatus", lastExecutionStatus);
        return stats;
    }
}